package Threads;

import java.sql.SQLException;
import java.sql.Statement;

import Windows.MainWindow;
import Config.Config;
import Judge.JudgeFunction;

public class JudgeThread extends Thread {

	public Statement sm=null;
	public String program="";
	public String InputOutput="";
	public int JudgeWaitTime=1000;
	public String serial="";
	
	public JudgeThread(Statement smt,String program,String InputOutput,int JudgeWaitTime,String serial) {
		super();
		this.sm=smt;
		this.program=program;
		this.InputOutput=InputOutput;
		this.JudgeWaitTime=JudgeWaitTime;
		this.serial=serial;
	}

	@Override
	public void run() {
		MainWindow.println("扫描到新的等待评测条目，serial="+serial+";现在开始评测，距离评测完成预计+"+(Config.CompileWaitTime+JudgeWaitTime+1000)+"ms;现在开始评测……");
		String ans="Unknow";
		try {
			String sqls1="UPDATE core SET state='JI',result='' WHERE SERIAL='"+serial+"'";
			sm.executeUpdate(sqls1);
			String result=JudgeFunction.JudgeJavaMData(serial, program, InputOutput, JudgeWaitTime);
			result=result.replaceAll("'",  "''");
			if(result.equals("AC")==true) {
				String s="UPDATE core SET state='AC',result='' WHERE SERIAL='"+serial+"'";
				sm.executeUpdate(s);
				ans="AC";
			}else if(result.equals("WA")==true){
				String s="UPDATE core SET state='WA',result='Program output and sample output is inconsistent!' WHERE SERIAL='"+serial+"'";
				sm.executeUpdate(s);
				ans="WA";
			}else if(result.substring(0, 2).equals("CE")==true){
				String s="UPDATE core SET state='CE',result='"+result.replaceAll("'","''")+"' WHERE SERIAL='"+serial+"'";
				sm.executeUpdate(s);
				ans="CE";
				MainWindow.println("评测条目serial="+serial+";评测完毕！结果是："+ans+";已经写入到数据库！");
				return ;
			}else{
				String s="UPDATE core SET state='RE',result='"+result+"' WHERE SERIAL='"+serial+"'";
				sm.executeUpdate(s);
				ans="WA";
			}
		} catch (Exception e) {
			MainWindow.println("评测过程中发生异常，标识："+serial+"  详细信息："+e);
			ans="IE";
			String s="UPDATE core SET state='CE',result='"+e.toString().replaceAll("'","''")+"' WHERE SERIAL='"+serial+"'";
			try {
				sm.executeUpdate(s);
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			return ;
		}
		MainWindow.println("评测条目serial="+serial+";评测完毕！结果是："+ans+";已经写入到数据库！");
	}

}
